//
//  DXHomeViewModel.swift
//  weiBoOfSwift
//
//  Created by simon on 15/12/10.
//  Copyright © 2015年 simon. All rights reserved.
//

import UIKit
import SVProgressHUD
class DXHomeViewModel: NSObject {
    
//    模型数组
    var statuseList:[DXStatuesViewModel]?
    
    var requestDataCount:Int = 0
    
    static let shareHomeViewModel = DXHomeViewModel()
    
    
    
}

// 首页网络请求数据方法
extension DXHomeViewModel{
    
    func loadHomeData(isPulling isPulling:Bool,isUping:Bool,callBack:(isSucess:Bool)->()){
        
        var maxid:Int64 = 0
        var sinceid:Int64 = 0
        if let max = statuseList?.last?.statuesMoel?.id where isPulling {
        
            maxid = max - 1
        }
        
        if let since = statuseList?.first?.statuesMoel?.id where isUping {
         sinceid = since
        }
        
        DXNetWorkClient.loadHomeData(maxid:maxid,sinceid:sinceid,sucessClosure:{ (responser) -> () in
//        logPrint(responser)
        
//        数据请求成功,判断返回来的是不是字典
        guard let statuseDict = responser as? [String : AnyObject] else{
            logPrint("loadHomeData 返回的不是字典")
        return
        }
//         取出字典中的statuse(dict)数组
        let statuses = statuseDict["statuses"] as! [[String : AnyObject]]
//         创建一个模型的数组statuse(model)
        var tempArray = [DXStatuesViewModel]()
        
        for stdict in statuses{
//           字典转模型
            let statuseModel = DXStatuseModel(dict: stdict)
            
            let statuseViewModel = DXStatuesViewModel(statues: statuseModel)
//            将模型添加到数组中
            tempArray.append(statuseViewModel)
        }
//            每次加载数据条数
            self.requestDataCount = tempArray.count
            
            if isPulling {
            self.statuseList = self.statuseList! + tempArray
            }else if isUping {
                
           self.statuseList = tempArray + self.statuseList!
            
            } else{
           self.statuseList = tempArray
            }
//        成功回调
        callBack(isSucess: true)
//        SVProgressHUD.dismiss()
        }) { (error) -> () in
//            SVProgressHUD.dismiss()
//            SVProgressHUD.showErrorWithStatus("数据请求失败")
            callBack(isSucess: false)

          logPrint(error)
        }
    
    }
    } 
    
    
    
    

